let handle = document.getElementById('handle')
let stop = document.getElementById('stop')
// let log = document.getElementById('log-area')
let bg = chrome.extension.getBackgroundPage()

// 持久化开关状态
let switchStatus = localStorage.getItem('switchStatus') || '0'
let storeSetting = localStorage.getItem('setting')
let setting = storeSetting === 'undefined' ? null : JSON.parse(storeSetting)
const switchInput = document.getElementById('mySwitch')
const slider = document.querySelector('.slider')
const checkbox = document.querySelector('input[type="checkbox"]') 
const switchText = document.querySelector('.switch-text')
const inputDom = document.getElementsByTagName('input')
const selectDom = document.getElementsByTagName('select')
if (setting) {
  inputDom[0].value = setting.priceMin
  inputDom[1].value = setting.priceMax
  inputDom[2].value = setting.total
  selectDom[0].value = setting.period
}

switchText.innerHTML = switchStatus === '0' ? '关' : '开'
switchInput.checked = switchStatus === '0' ? false : true
slider.addEventListener('click', function() {
  if (switchStatus === '0') {
    switchText.innerHTML = '开'
    switchInput.checked = false
    switchStatus = '1'
    // 执行searcBtn脚本
    setting = {
      period: selectDom[0].value,
      priceMin: inputDom[0].value,
      priceMax: inputDom[1].value,
      total: inputDom[2].value
    }
    if (setting.priceMin === '' || setting.priceMax === '') {
      $('#place').before('<li style="color: red;">请输入电价比例系数范围</li>')
      return
    }
    if (setting.total === '') {
      $('#place').before('<li style="color: red;">请输入预计摘牌总电量</li>')
      return
    }
    if (setting.priceMin < 0.8 || setting.priceMax > 1.2 || setting.priceMin > setting.priceMax) {
      $('#place').before('<li style="color: red;">电价比例系数范围为0.8到1.2且最小值不能大于最大值</li>')
      return
    }
    if (hasNoMaxFourDecimals(setting.priceMin) || hasNoMaxFourDecimals(setting.priceMax)) {
      $('#place').before('<li style="color: red;">电价比例系数最多为四位小数</li>')
      return
    }
    chrome.tabs.query({
      active: true,
      currentWindow: true,
    }, (tabs) => {
      chrome.scripting.executeScript({
        args: [setting],
        target: { tabId: tabs[0].id },
        func: (setting) => {
          searchBtn(setting)
        }
      })
    })
  } else {
    switchText.innerHTML = '关'
    switchInput.checked = true
    switchStatus = '0'
    $('#log-ul li:not(:last)').remove()
    chrome.tabs.query({
      active: true,
      currentWindow: true,
    }, (tabs) => {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        func: () => {
          stopExecute()
        }
      })
    })
  }
  console.log(4, setting);
  localStorage.setItem('setting', JSON.stringify(setting))
  localStorage.setItem('switchStatus', switchStatus)
})

// handle.addEventListener('click', (event) => {
//   const inputDom = document.getElementsByTagName('input')
//   const selectDom = document.getElementsByTagName('select')
//   var setting = {
//     period: selectDom[0].value,
//     priceMin: inputDom[0].value,
//     priceMax: inputDom[1].value
//   }
//   const errDom = document.getElementsByClassName('err-msg')[0]
//   if (inputDom[0].value > inputDom[1].value) {
//     errDom.innerHTML = '电价最小值不能大于电价最大值'
//     errDom.style.display = 'block'
//   } else {
//     errDom.style.display = 'none'
//   }

//   chrome.tabs.query({
//     active: true,
//     currentWindow: true,
//   }, (tabs) => {
//     chrome.scripting.executeScript({
//       args: [setting],
//       target: { tabId: tabs[0].id },
//       func: (setting) => {
//         searchBtn(setting)
//       }
//     })
//   })
// })

// stop.addEventListener('click', (event) => {
//   chrome.tabs.query({
//     active: true,
//     currentWindow: true,
//   }, (tabs) => {
//     chrome.scripting.executeScript({
//       args: [],
//       target: { tabId: tabs[0].id },
//       func: () => {
//         if (intervalID) {
//           clearInterval(intervalID)
//           console.log('任务停止')
//         } else {
//           Toast('没有在执行的任务')
//         }
//       }
//     })
//   })
//   $('#place').before('<li style="color: red;">任务被手动停止</li>')
//   gotoBottom()
// })

chrome.runtime.onMessage.addListener((data, sender, response) => {
  console.log(data)
  if (data.type === 'info') {
    $('#place').before('<li>' + data.msg + '</li>')
  }else if (data.type === 'success') {
    $('#place').before('<li style="color: green;">' + data.msg + '</li>')
  }
  else if (data.type === 'error') {
    $('#place').before('<li style="color: red;">' + data.msg + '</li>')
  }
  gotoBottom()
})
function gotoBottom() {
  let scrollHeight = $('#log-ul').prop('scrollHeight')
  if (scrollHeight > $('#log-ul').prop('clientHeight')) {
    $('#log-ul').scrollTop(scrollHeight, 200)
  }
}

function hasNoMaxFourDecimals(num) {  
  const str = num.toString()
  const match = str.match(/\./g)
  if (match) {
    if (match.length === 1 && str.split('.')[1].length <= 4) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}